#include "touch.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/input.h>
#include <string.h>

static int touch_fd = -1;
static pthread_t touch_thread;
static int running = 0;

static int touch_x = -1;
static int touch_y = -1;



// 触摸线程函数
static void *touch_thread_func(void *arg)
{
    struct input_event ev;
    int x = -1, y = -1;
    int is_down = 0;
    int last_is_down = 0;

    while (running)
    {
        int rd = read(touch_fd, &ev, sizeof(ev));
        if (rd != sizeof(ev))
            continue;

        if (ev.type == EV_ABS)
        {
            if (ev.code == ABS_MT_POSITION_X || ev.code == ABS_X)
                x = ev.value;
            else if (ev.code == ABS_MT_POSITION_Y || ev.code == ABS_Y)
                y = ev.value;
        }
        else if (ev.type == EV_KEY && ev.code == BTN_TOUCH)
        {
            is_down = ev.value;

            // 抬起瞬间执行 CLICK_UP
            if (!is_down && last_is_down && x != -1 && y != -1)
            {
                printf("[TOUCH] CLICK_UP at (%d, %d)\n", x, y);
                click_event(x, y, CLICK_UP);
            }

            last_is_down = is_down;
        }
        else if (ev.type == EV_SYN && ev.code == SYN_REPORT)
        {
            // 只要处于按下状态，持续执行 CLICK_DOWN
            if (is_down && x != -1 && y != -1)
            {
                touch_x = x;
                touch_y = y;
                printf("[TOUCH] CLICK_DOWN at (%d, %d)\n", x, y);
                click_event(x, y, CLICK_DOWN_ING);
            }
        }
    }

    return NULL;
}
int touch_init(const char *event_path)
{
    if (running)
        return 0;

    touch_fd = open(event_path, O_RDONLY);
    if (touch_fd < 0)
    {
        perror("open touch input");
        return -1;
    }

    running = 1;
    if (pthread_create(&touch_thread, NULL, touch_thread_func, NULL) != 0)
    {
        perror("pthread_create");
        close(touch_fd);
        running = 0;
        return -1;
    }

    printf("[touch] listening on %s ...\n", event_path);
    return 0;
}

void touch_stop(void)
{
    if (!running)
        return;

    running = 0;
    pthread_join(touch_thread, NULL);
    close(touch_fd);
    touch_fd = -1;
    printf("[touch] stopped.\n");
}
